package cn.fntop.filter;

import cn.fntop.context.TenantContextHolder;
import cn.fntop.constant.TenantConstants;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 根据租户id动态切换数据源
 */
@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class TenantContextHolderFilter extends GenericFilterBean {

    @SneakyThrows
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
        try {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            String headerTenantId = request.getHeader(TenantConstants.TENANT_ID);
            String paramTenantId = request.getParameter(TenantConstants.TENANT_ID);
            log.info("获取租户ID => headerTenantId {},paramTenantId {}", headerTenantId, paramTenantId);
            log.info("接口过滤执行 uri => {}", request.getRequestURI());
            Integer tenantId = TenantConstants.TENANT_ID_1;
            if (StrUtil.isNotBlank(headerTenantId)) {
                tenantId = Integer.parseInt(headerTenantId);
            } else if (StrUtil.isNotBlank(paramTenantId)) {
                tenantId = Integer.parseInt(paramTenantId);
            }
            String ds = TenantConstants.DS.DS1.getDsKey(tenantId);
            ds = ds == null ? "test1" : ds;
            log.info("获取租户ID {},租户数据库 {}", tenantId, ds);

            TenantContextHolder.setTenantId(tenantId);
            DynamicDataSourceContextHolder.push(ds);
            filterChain.doFilter(request, response);
        } finally {
            DynamicDataSourceContextHolder.poll();
            TenantContextHolder.clear();
        }
    }
}
